Certainly! Here are a few examples of how the else if statement can be used in Java to handle multiple conditions:
Example 1: Grading System
Grading system using if else in java
public class Main{
public static void main(String[] args) {
int marks = 80;
if (marks >= 90) {
System.out.println("Grade: A");
} else if (marks >= 80) {
System.out.println("Grade: B");
} else if (marks >= 70) {
System.out.println("Grade: C");
} else if (marks >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
}
}
Output
Grade: B
In this example, the marks is 80. So the first if condition will fail as it is less than 90, the second if else condition will execute because mark is equal to 80. The rest of the statements will not be executed as the second one passes the condition.
The output will be
Grade: B
Example 2: Time of Day Greeting
Greeting example in java
public class Main{
public static void main(String[] args) {
int time = 15;
if (time < 12) {
System.out.println("Good morning!");
} else if (time < 18) {
System.out.println("Good afternoon!");
} else {
System.out.println("Good evening!");
}
}
}
Output
Good afternoon!
In this example, the given time is 15. So the first if condition will fails because time is greater than 12. The second one will be executed as it is less than 18 and give the output as
Good afternoon!.
Example 3: Categorizing Numbers
Categorizing Numbers example in java
public class Main{
public static void main(String[] args) {
int number = 7;
if (number == 0) {
System.out.println("Number is zero.");
} else if (number % 2 == 0) {
System.out.println("Number is even.");
} else {
System.out.println("Number is odd.");
}
}
}
Output
Number is odd.
In this example, the given number is 7. The first condition will fails because it is not zero. The 7 modulo 2 value is 1. So the second else if condition will not be executed. Else wil be executed at last as no defined
condition passes and the output will be
Number is odd.
Example 4: Age Groups
Find the age category example in java
public class Main{
public static void main(String[] args) {
int age = 25;
if (age < 18) {
System.out.println("You are a minor.");
} else if (age >= 18 && age < 60) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a senior citizen.");
}
}
}
Output
You are an adult.
In this example, the given age is 25. The first condition will fails as it is greater than 18 and checks the second condition. The age will lies betweeen 18 and 60 so it will be executed
and the output will be
You are an adult.
In these examples, the else if statements allow the program to evaluate multiple conditions sequentially. The first true condition's block of code is executed, and the rest of the else if and else blocks are skipped. This enables the program to make more nuanced decisions and handle a variety of scenarios based on the values of different variables or conditions.